package org.bdware.irp.irplib.crypto;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import org.apache.log4j.Logger;
import org.bdware.irp.irplib.core.IrpMessage;
import org.bdware.irp.irplib.core.IrpMessageEnvelope;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class NettyTCPCodeC extends MessageToMessageCodec<ByteBuf, IrpMessage> {

    Logger logger = Logger.getLogger(NettyTCPCodeC.class);
    HashMap<Integer,AbstractPacketReceiveBuffer> receiveBufferMap = new HashMap<>();

    @Override
    protected void encode(ChannelHandlerContext ctx, IrpMessage msg, List<Object> out){
        try {
            ByteBuf buff = Unpooled.directBuffer();
            IrpMessagePacket messsagePacket = IrpMessagePacket.irpMessageToTCPPackets(msg);
            logger.debug("encoding IRP message to byteBuffer, msg opcode: " + msg.header.opCode +
                    ", msg body length: " + messsagePacket.bodyPacket.length);
            buff.writeBytes(IrpMessagePacket.toBytes(messsagePacket));
            logger.debug("finish encoding, packet length: " + buff.readableBytes());
            out.add(buff);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out){
        //logger.debug("decoding byteBuffer to IRP message");
        try {

            byte[] packetBytes = new byte[msg.readableBytes()];
            msg.readBytes(packetBytes);
            IrpMessagePacket packet = IrpMessagePacket.bytesToMessagePacket(packetBytes);
            out.add(IrpMessagePacket.packetTCPToIrpMessage(packet));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
